package mydessertstore.web.servlet;

import mydessertstore.domain.Account;
import mydessertstore.domain.Cart;
import mydessertstore.domain.Order;
import mydessertstore.service.LogService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

public class NewOrderFormServlet extends HttpServlet {
    private static final String NEW_ORDER_FORM = "/WEB-INF/jsp/order/newOrder.jsp";
    private static final String SIGN_ON_FORM = "/WEB-INF/jsp/account/signon.jsp";
    protected static final String ERROR = "/WEB-INF/jsp/common/error.jsp";

    private  Order order ;
    private Account account;
    private Cart cart;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset = UTF-8");


        HttpSession session = req.getSession();
        account = (Account) session.getAttribute("account");
        cart = (Cart) session.getAttribute("cart");

        if(account == null){
            session.setAttribute("message", "You must sign on before attempting to check out.  Please sign on and try checking out again.");
            req.getRequestDispatcher(SIGN_ON_FORM).forward(req, resp);
        }else if(cart !=null){
            order = new Order();
            order.initOrder(account, cart);
            session.setAttribute("order", order);



            if(account!=null) {

                LogService logService = new LogService();

                String logInfo = logService.logInfo(" ") + " 跳转到新订单页面 " ;
                logService.insertLogInfo(account.getUsername(), logInfo);
            }
            else{
                LogService logService = new LogService();
                String logInfo = logService.logInfo(" ") + " 跳转到新订单页面 " ;
                logService.insertLogInfo("未登录用户", logInfo);
            }
            //日志结束

            req.getRequestDispatcher(NEW_ORDER_FORM).forward(req, resp);
        }
        else{
            session.setAttribute("message", "An order could not be created because a cart could not be found.");

            //日志功能
            if(account!=null) {

                LogService logService = new LogService();

                String logInfo = logService.logInfo(" ") + " 生成订单页面信息错误 " ;
                logService.insertLogInfo(account.getUsername(), logInfo);
            }
            else{
                LogService logService = new LogService();
                String logInfo = logService.logInfo(" ") + " 生成订单页面信息错误 " ;
                logService.insertLogInfo("未登录用户", logInfo);
            }
            //日志结束

            req.getRequestDispatcher(ERROR).forward(req, resp);
        }


    }
}
